<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.1.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","width":300,"display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="本篇为Java线程池ThreadPoolExecutor学习的第二篇。该篇介绍了线程池工作原理以及线程池执行任务的源码分析。">
<meta property="og:type" content="article">
<meta property="og:title" content="Java线程池之ThreadPoolExecutor（二）">
<meta property="og:url" content="http://example.com/2020/10/08/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor2/index.html">
<meta property="og:site_name" content="履歴の本文">
<meta property="og:description" content="本篇为Java线程池ThreadPoolExecutor学习的第二篇。该篇介绍了线程池工作原理以及线程池执行任务的源码分析。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/2020/10/08/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor2/000.png">
<meta property="og:image" content="http://example.com/2020/10/08/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor2/001.png">
<meta property="article:published_time" content="2020-10-08T03:31:44.000Z">
<meta property="article:modified_time" content="2020-10-21T03:20:42.013Z">
<meta property="article:author" content="モンキーDルフィ">
<meta property="article:tag" content="线程池">
<meta property="article:tag" content="多线程">
<meta property="article:tag" content="高并发">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/2020/10/08/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor2/000.png">

<link rel="canonical" href="http://example.com/2020/10/08/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor2/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Java线程池之ThreadPoolExecutor（二） | 履歴の本文</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">履歴の本文</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">天下风云出我辈，一入代码岁月催</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">15</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">7</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">18</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2020/10/08/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/lufei.jpg">
      <meta itemprop="name" content="モンキーDルフィ">
      <meta itemprop="description" content="海贼王におれはなる！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="履歴の本文">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java线程池之ThreadPoolExecutor（二）
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-10-08 11:31:44" itemprop="dateCreated datePublished" datetime="2020-10-08T11:31:44+08:00">2020-10-08</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/" itemprop="url" rel="index"><span itemprop="name">并发编程</span></a>
                </span>
            </span>

          
            <span id="/2020/10/08/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor2/" class="post-meta-item leancloud_visitors" data-flag-title="Java线程池之ThreadPoolExecutor（二）" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2020/10/08/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor2/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2020/10/08/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor2/" itemprop="commentCount"></span>
    </a>
  </span>
  
  
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
              <span>9.2k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
              <span>8 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>本篇为Java线程池ThreadPoolExecutor学习的第二篇。该篇介绍了线程池工作原理以及线程池执行任务的源码分析。</p>
<a id="more"></a>

<h2 id="A-Story-Mapping-Thread-Pool"><a href="#A-Story-Mapping-Thread-Pool" class="headerlink" title="A Story Mapping Thread Pool"></a>A Story Mapping Thread Pool</h2><p>关于线程池的工作原理，不知你是否听过老王开屠宰场雇屠夫杀猪的故事。只因太过经典，笔者这里仍旧依托于此展开讲解。但相信我，这将是你听过此故事的最生动、最详细的版本。</p>
<pre><code>老王原本是一个屠夫，本想靠着手艺本本分分过一辈子，怎奈突如其来的拆迁让他一夜之间变成了一个暴发户。俗话说的好，做人如果没有梦
想，那和咸鱼有什么分别呢？老王或许不止一次的“幻想”过要是自己能开一个屠宰场，再雇一群屠夫干活，自己当老板那该有多好啊！这下好
了，拆迁有了启动资金，老王便风风火火地开始了屠宰场的建造。可毕竟穷了大半辈子，老王不敢梭哈将全部手笔都用在屠宰场的建设上，因
此屠宰场的规模也不算太大——有5个主杀猪台、一个能装10头猪的猪圈以及5个备用杀猪台。Ok，屠宰场有了，接下来就该联系业务（联系养猪
场送猪过来）和招募屠夫了。老王广告打的效果不错，第二天一早就有一头猪被送过来了，与此同时，有一个屠夫（屠夫A）前来应聘。老王
一想那正好啊，就让他来杀吧，刚好试试他的手艺。于是屠夫A就上了主杀猪台，三下五除二就把猪给杀了，丝毫不拖泥带水。老王甚是欢
喜，当即决定录用其为正式员工。
第二天一早，又有一头猪被送过来。屠夫A赶忙走向主杀猪台，准备操刀开干。老王一把将其拉住，说道：现在咱们刚开业，业务还不忙。况
且通过昨天的表现，你已经向我证明了你的技术，现在也就没必要着急杀这一头两头的猪了。相反，当务之急是招募屠夫，快速形成既定的生
产力。说着说着，屠夫B来应聘了。同样地，老王让其上台杀猪，自己则和屠夫A在一旁看着。屠夫B也顺利通过考核，成为正式员工。就这
样，每位屠夫只在应聘考核中杀过第一头猪，然后大家一起招募其他屠夫......直到招够了5个屠夫A、B、C、D、E。既定生产力已然成型，接
下来就是有序的生产阶段。
一个好的公司是需要一个好的领导的，老王或许在自己的杀猪生涯中有过以下困扰：自己正在杀猪，马上就要杀完可以休息会了。这时突然又
来了一车猪，就在眼前嗷嗷直叫，顿时内心一股火就上来了。杀归杀，身为屠夫这是无可厚非的，但是人总是有惰性的嘛！这样难免影响心
情，转而影响工作的效率。老王想到了一个好主意，不管屠夫手上有没有猪，送来的猪统统都先到猪圈中去。谁的手中没有猪了，就去猪圈中
看一眼，有猪的话就取一头来杀，没有的话就去休息（下一批猪来的时候会被通知）。这样大家的工作变被动为主动，生产效率无形之中又得
到了提升。
五个屠夫各自站在一个主杀猪台前，熟练地杀着猪。就这样一天一天过去了，老王的业务渐渐有所起步。平日里，几个屠夫基本没有闲暇，猪
圈里一直处于有猪的状态，但是不多，五个屠夫勉强还能周转的开。但是逢年过节的时候，五个屠夫彻底忙不过来了，猪圈里的猪也达到了上
限10个，不能再往里放了。那么，再送来的猪怎么办呢？总不能到手的生意不做吧！老王深谋远虑，那五个备用杀猪台就是为此而准备的！只
有杀猪台也不行啊，于是老王决定招聘5个临时工来解决燃眉之急。5个正式工，5个临时工，10个屠夫差不多算是够用了。如果实在是还不够
用，那没办法！老王说这生意老子不做了好吧，哪来的猪你给我回哪去。等节假日一过去，不忙了再将临时工辞退掉，又回归了正常的生产状
态......</code></pre>
<p>故事到这里就讲完了，里面其实有许多细节和巧妙的地方，需要读者细细品味……</p>
<h2 id="Principle-Of-Thread-Pool"><a href="#Principle-Of-Thread-Pool" class="headerlink" title="Principle Of Thread Pool"></a>Principle Of Thread Pool</h2><p>线程池的工作原理如下如所示：<br><img src="/2020/10/08/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor2/000.png" alt="000"></p>
<ol>
<li>首先创建核心线程，直到workerCount达到corePoolSize</li>
<li>然后将任务放入阻塞队列，直到队列塞满</li>
<li>继续创建线程（非核心），直到workCount达到maximumPoolSize</li>
<li>执行拒绝策略，默认为AbortPolicy</li>
</ol>
<h2 id="The-Source-Code-Parsing"><a href="#The-Source-Code-Parsing" class="headerlink" title="The Source Code Parsing"></a>The Source Code Parsing</h2><p>我们从threadPoolExecutor.execute(task)入手，一步一步地进行源码的剖析，力求从根本上理解并掌握线程池的实现原理。</p>
<h3 id="execute"><a href="#execute" class="headerlink" title="execute"></a>execute</h3><p>该方法是线程池执行任务的入口方法，从整体上体现了线程池的工作原理。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">execute</span><span class="params">(Runnable command)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (command == <span class="keyword">null</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> c = ctl.get();</span><br><span class="line">    <span class="keyword">if</span> (workerCountOf(c) &lt; corePoolSize) &#123; <span class="comment">// 1.如果工作线程数小于核心线程数，则尝试创建核心线程执行任务，创建成功直接返回</span></span><br><span class="line">        <span class="keyword">if</span> (addWorker(command, <span class="keyword">true</span>))</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        c = ctl.get();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (isRunning(c) &amp;&amp; workQueue.offer(command)) &#123; <span class="comment">// 2.如果工作线程数不小于核心线程数并且线程池处于可运行状态，则尝试任务入队</span></span><br><span class="line">        <span class="keyword">int</span> recheck = ctl.get();</span><br><span class="line">        <span class="keyword">if</span> (! isRunning(recheck) &amp;&amp; remove(command)) <span class="comment">// 入队成功，但是线程池变成了非运行状态，则尝试任务出队并执行拒绝策略</span></span><br><span class="line">            reject(command);</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (workerCountOf(recheck) == <span class="number">0</span>) <span class="comment">// 此时工作线程数为0（异常销毁），没有线程来执行任务，怎么办？只能新建一个线程来执行</span></span><br><span class="line">            addWorker(<span class="keyword">null</span>, <span class="keyword">false</span>); <span class="comment">// 为什么是非核心线程呢？其实这里是核心还是非核心没有什么区别，目的就是确保创建出新线程来执行任务</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (!addWorker(command, <span class="keyword">false</span>)) <span class="comment">// 3.如果入队失败，尝试创建非核心线程执行任务，创建失败则执行拒绝策略</span></span><br><span class="line">        reject(command);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="addWorker"><a href="#addWorker" class="headerlink" title="addWorker"></a>addWorker</h3><p>这个方法乍一看很唬人，上来就是一段双层for循环，其实也比较简单，它主要做了两件事情：</p>
<ol>
<li>CAS操作将工作线程数增加1</li>
<li>创建一个Worker并启用</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">addWorker</span><span class="params">(Runnable firstTask, <span class="keyword">boolean</span> core)</span> </span>&#123;</span><br><span class="line">    <span class="comment">/****************************************************first logic****************************************************/</span></span><br><span class="line">    retry:</span><br><span class="line">    <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">        <span class="keyword">int</span> c = ctl.get();</span><br><span class="line">        <span class="keyword">int</span> rs = runStateOf(c);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 当线程池处于非运行状态时候，通常是不允许再去创建线程的。除了以下这种情况：</span></span><br><span class="line"><span class="comment">         *  1.线程池处于SHUTDOWN状态（不能添加新任务，但还能继续执行已经添加的任务）</span></span><br><span class="line"><span class="comment">         *  2.本次要添加的任务为空</span></span><br><span class="line"><span class="comment">         *  3.阻塞队列不为空（存在已经添加的任务）</span></span><br><span class="line"><span class="comment">         * 这是什么意思呢？说白了就是我这次要创建的线程不是为了要执行新添加的任务，而是去执行已经存在的任务。</span></span><br><span class="line"><span class="comment">         * 这个逻辑正好呼应了execute方法中else if (workerCountOf(recheck) == 0)的情况。</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">if</span> (rs &gt;= SHUTDOWN &amp;&amp; <span class="comment">// 线程处于非运行状态</span></span><br><span class="line">            ! (rs == SHUTDOWN &amp;&amp; firstTask == <span class="keyword">null</span> &amp;&amp; ! workQueue.isEmpty())) <span class="comment">// 排除特殊情况</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">            <span class="keyword">int</span> wc = workerCountOf(c);</span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * 对线程池当前线程数的判断：</span></span><br><span class="line"><span class="comment">             *  1.当前线程数达到线程池容量时，无法创建新线程</span></span><br><span class="line"><span class="comment">             *  2.如果是核心线程，判断当前线程数有没有达到corePoolSize，如果达到了则无法创建新线程</span></span><br><span class="line"><span class="comment">             *  3.如果是非核心线程，判断当前线程数有没有达到maximumPoolSize，如果达到了则无法创建新线程</span></span><br><span class="line"><span class="comment">             * 其实在这里就能看出来，所谓的核心线程与非核心线程，其实就是创建顺序的先后，没有达到corePoolSize</span></span><br><span class="line"><span class="comment">             * 时创建的线程都是核心线程，之后创建的都是非核心线程。</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">if</span> (wc &gt;= CAPACITY ||</span><br><span class="line">                wc &gt;= (core ? corePoolSize : maximumPoolSize))</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            <span class="keyword">if</span> (compareAndIncrementWorkerCount(c)) <span class="comment">// 如果CAS修改workerCount成功的话，直接退出最外层循环，走第二段逻辑</span></span><br><span class="line">                <span class="keyword">break</span> retry;</span><br><span class="line">            c = ctl.get();</span><br><span class="line">            <span class="keyword">if</span> (runStateOf(c) != rs) <span class="comment">// 如果线程池的运行状态发生了改变，则重走外层循环（需要再次根据线程池的状态判断能否创建线程），否则继续内层循环不断尝试CAS</span></span><br><span class="line">                <span class="keyword">continue</span> retry;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/****************************************************second logic****************************************************/</span></span><br><span class="line">    <span class="keyword">boolean</span> workerStarted = <span class="keyword">false</span>; <span class="comment">// 是否已经启动的标志位</span></span><br><span class="line">    <span class="keyword">boolean</span> workerAdded = <span class="keyword">false</span>; <span class="comment">// 是否已经添加的标志位</span></span><br><span class="line">    Worker w = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        w = <span class="keyword">new</span> Worker(firstTask); <span class="comment">// 构建一个Worker，将任务封装进去（至于Worker是什么，后面会重点解析）</span></span><br><span class="line">        <span class="keyword">final</span> Thread t = w.thread; <span class="comment">// 获取工作线程</span></span><br><span class="line">        <span class="keyword">if</span> (t != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">final</span> ReentrantLock mainLock = <span class="keyword">this</span>.mainLock;</span><br><span class="line">            mainLock.lock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">int</span> rs = runStateOf(ctl.get());</span><br><span class="line">                <span class="comment">/**</span></span><br><span class="line"><span class="comment">                 * 只有在RUNNING状态下或者SHUTDOWN状态且当前任务为空时（代表要去执行已经添加的任务）才可以增加一个Worker</span></span><br><span class="line"><span class="comment">                 */</span></span><br><span class="line">                <span class="keyword">if</span> (rs &lt; SHUTDOWN ||</span><br><span class="line">                    (rs == SHUTDOWN &amp;&amp; firstTask == <span class="keyword">null</span>)) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (t.isAlive()) <span class="comment">// 任务刚封装进Worker，工作线程还没启动，状态就是alive了？显然要抛出异常</span></span><br><span class="line">                        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalThreadStateException();</span><br><span class="line">                    workers.add(w); <span class="comment">// 正式添加一个Worker</span></span><br><span class="line">                    <span class="keyword">int</span> s = workers.size();</span><br><span class="line">                    <span class="keyword">if</span> (s &gt; largestPoolSize) <span class="comment">// 动态修改线程池的最大实际容量，这算是一个线程池监控的指标吧</span></span><br><span class="line">                        largestPoolSize = s;</span><br><span class="line">                    workerAdded = <span class="keyword">true</span>; <span class="comment">// 修改标志位</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                mainLock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (workerAdded) &#123;</span><br><span class="line">                t.start(); <span class="comment">// 正式启动工作线程</span></span><br><span class="line">                workerStarted = <span class="keyword">true</span>; <span class="comment">// 修改标志位</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (! workerStarted) <span class="comment">// 线程执行抛出异常，导致标志位修改失败</span></span><br><span class="line">            addWorkerFailed(w); <span class="comment">// 异常之后的处理：将Worker移除、workerCount减一</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> workerStarted;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Worker"><a href="#Worker" class="headerlink" title="Worker"></a>Worker</h3><p>Worker是ThreadPoolExecutor的内部类，其源码如下（忽略AQS相关特性）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Worker</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">6138294804551838833L</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/** 当前Worker要执行的线程 */</span></span><br><span class="line">    <span class="keyword">final</span> Thread thread;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/** 初始化时要执行的任务，可以为空 */</span></span><br><span class="line">    Runnable firstTask;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/** 计数器：已执行的任务数 */</span></span><br><span class="line">    <span class="keyword">volatile</span> <span class="keyword">long</span> completedTasks;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 构造函数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    Worker(Runnable firstTask) &#123;</span><br><span class="line">        <span class="keyword">this</span>.firstTask = firstTask; <span class="comment">// 赋值首次要执行的任务</span></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 赋值要执行的线程。我们可以看到Worker实现了Runnable，</span></span><br><span class="line"><span class="comment">         * 其本身也是一个任务，此处创建线程时传入的参数就是Worker</span></span><br><span class="line"><span class="comment">         * 自身。换句话说，如果执行thread的start()方法，实际上</span></span><br><span class="line"><span class="comment">         * 就会执行Worker的run()方法。</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">this</span>.thread = getThreadFactory().newThread(<span class="keyword">this</span>); </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        runWorker(<span class="keyword">this</span>); <span class="comment">// 内部类调用外部类的方法</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="runWorker"><a href="#runWorker" class="headerlink" title="runWorker"></a>runWorker</h3><p>这个方法是线程池真正执行任务的方法，也体现了线程复用的原理。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">runWorker</span><span class="params">(Worker w)</span> </span>&#123;</span><br><span class="line">    Thread wt = Thread.currentThread();</span><br><span class="line">    Runnable task = w.firstTask;</span><br><span class="line">    w.firstTask = <span class="keyword">null</span>;</span><br><span class="line">    w.unlock();</span><br><span class="line">    <span class="keyword">boolean</span> completedAbruptly = <span class="keyword">true</span>; <span class="comment">// 是否为异常完成</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 注意这个while循环，正是这里实现了线程的复用。</span></span><br><span class="line"><span class="comment">         * task初始为Worker的初始任务，也就是第一次循环会先执行Worker自带的任务，</span></span><br><span class="line"><span class="comment">         * 然后task = getTask()，也就是之后的循环会从阻塞队列中去取任务执行，直</span></span><br><span class="line"><span class="comment">         * 到队列中不再有任务。</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">while</span> (task != <span class="keyword">null</span> || (task = getTask()) != <span class="keyword">null</span>) &#123;</span><br><span class="line">            w.lock();</span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * 这段逻辑比较绕，但是目的无非有两点：</span></span><br><span class="line"><span class="comment">             *  1.如果线程池已经停止（状态为STOP及以上），确保线程被中断</span></span><br><span class="line"><span class="comment">             *  2.如果线程池没有停止（状态为RUNNING或者SHUTDOWN），确保线程不被中断</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">if</span> ((runStateAtLeast(ctl.get(), STOP) ||</span><br><span class="line">                    (Thread.interrupted() &amp;&amp; runStateAtLeast(ctl.get(), STOP))) &amp;&amp; </span><br><span class="line">                    !wt.isInterrupted())</span><br><span class="line">                wt.interrupt();</span><br><span class="line">            <span class="keyword">try</span> &#123; <span class="comment">// 异常处理第二层，没做任何处理，自动往上抛</span></span><br><span class="line">                beforeExecute(wt, task); <span class="comment">// 执行任务前置操作（空实现，可被重写）</span></span><br><span class="line">                Throwable thrown = <span class="keyword">null</span>;</span><br><span class="line">                <span class="keyword">try</span> &#123; <span class="comment">// 异常处理第一层，捕获异常，继续往上抛</span></span><br><span class="line">                    task.run(); <span class="comment">// 真正执行任务</span></span><br><span class="line">                &#125; <span class="keyword">catch</span> (RuntimeException x) &#123;</span><br><span class="line">                    thrown = x; <span class="keyword">throw</span> x;</span><br><span class="line">                &#125; <span class="keyword">catch</span> (Error x) &#123;</span><br><span class="line">                    thrown = x; <span class="keyword">throw</span> x;</span><br><span class="line">                &#125; <span class="keyword">catch</span> (Throwable x) &#123;</span><br><span class="line">                    thrown = x; <span class="keyword">throw</span> <span class="keyword">new</span> Error(x);</span><br><span class="line">                &#125; <span class="keyword">finally</span> &#123; <span class="comment">// finally第一层</span></span><br><span class="line">                    afterExecute(task, thrown); <span class="comment">// 执行任务后置操作（空实现，可被重写）</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123; <span class="comment">// finally第二层</span></span><br><span class="line">                task = <span class="keyword">null</span>; <span class="comment">// task置空，为了跳过while判断的第一步，从而向队列中取任务</span></span><br><span class="line">                w.completedTasks++; <span class="comment">// 无论任务执行是否出现异常，已执行任务数都加一</span></span><br><span class="line">                w.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 如果能走到这里，说明任务执行没有发生异常，修改标志位</span></span><br><span class="line">        completedAbruptly = <span class="keyword">false</span>;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123; <span class="comment">// finally第三层</span></span><br><span class="line">        processWorkerExit(w, completedAbruptly); <span class="comment">// 处理Worker的退出</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="processWorkerExit"><a href="#processWorkerExit" class="headerlink" title="processWorkerExit"></a>processWorkerExit</h3><p>当线程正常退出（阻塞队列中没有任务再需要执行）或者异常退出（任务执行中发生异常）时，都会走到这个方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">processWorkerExit</span><span class="params">(Worker w, <span class="keyword">boolean</span> completedAbruptly)</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 如果线程是异常退出的，那么需要将workCount减一</span></span><br><span class="line"><span class="comment">     * 如果线程是正常退出的，则早在getTask()方法中就进行了该操作，此处无需重复</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">if</span> (completedAbruptly)</span><br><span class="line">        decrementWorkerCount();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> ReentrantLock mainLock = <span class="keyword">this</span>.mainLock;</span><br><span class="line">    mainLock.lock();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        completedTaskCount += w.completedTasks; <span class="comment">// 汇总完成的任务数</span></span><br><span class="line">        workers.remove(w); <span class="comment">// 将Worker从集合中移除</span></span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        mainLock.unlock();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    tryTerminate();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> c = ctl.get();</span><br><span class="line">    <span class="keyword">if</span> (runStateLessThan(c, STOP)) &#123; <span class="comment">// 线程池状态为RUNNING或者SHUTDOWN</span></span><br><span class="line">        <span class="keyword">if</span> (!completedAbruptly) &#123; <span class="comment">// 正常退出时</span></span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * 如果allowCoreThreadTimeOut为true，代表允许核心线程超时退出，此时工作线程允许的最小值为0。</span></span><br><span class="line"><span class="comment">             * 如果allowCoreThreadTimeOut为false，代表不允许核心线程超时退出，此时工作线程允许的最小值为corePoolSize。</span></span><br><span class="line"><span class="comment">             * 当工作线程允许的最小值为0并且阻塞队列不为空时，该最小值变为1，意为至少应该有一个线程执行已经添加的任务。</span></span><br><span class="line"><span class="comment">             * Ok，最小工作线程数确定了，现在就要判断当前工作线程数是否够数了。如果够数，直接返回，线程退出完毕。否则，</span></span><br><span class="line"><span class="comment">             * 补充创建一个Worker继续工作！</span></span><br><span class="line"><span class="comment">             * </span></span><br><span class="line"><span class="comment">             * 我们试想一下allowCoreThreadTimeOut为false的情况，核心线程是如何做到永远不退出的呢？其实它们会一直进行</span></span><br><span class="line"><span class="comment">             * runWorker()方法的while循环，当阻塞队列中没有任务时，它们就会一直阻塞在那里，直到有任务了再继续执行。</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="keyword">int</span> min = allowCoreThreadTimeOut ? <span class="number">0</span> : corePoolSize;</span><br><span class="line">            <span class="keyword">if</span> (min == <span class="number">0</span> &amp;&amp; ! workQueue.isEmpty())</span><br><span class="line">                min = <span class="number">1</span>;</span><br><span class="line">            <span class="keyword">if</span> (workerCountOf(c) &gt;= min)</span><br><span class="line">                <span class="keyword">return</span>; <span class="comment">// 这里就代表任务执行完毕，线程生命周期走到了尽头......</span></span><br><span class="line">        &#125;</span><br><span class="line">        addWorker(<span class="keyword">null</span>, <span class="keyword">false</span>); <span class="comment">// 异常退出时，相当于时Worker和任务同归于尽了，因此需要补充创建一个工作线程</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="getTask"><a href="#getTask" class="headerlink" title="getTask"></a>getTask</h3><p>该方法为从阻塞队列中获取任务的方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> Runnable <span class="title">getTask</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">boolean</span> timedOut = <span class="keyword">false</span>; <span class="comment">// 是否超时的标志位</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">        <span class="keyword">int</span> c = ctl.get();</span><br><span class="line">        <span class="keyword">int</span> rs = runStateOf(c);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 如果线程池的状态为STOP及以上，就无法再执行已经存在的任务。</span></span><br><span class="line">        <span class="comment">// 当然如果队列中本身就已经没有了任务，自然也不需要执行了。</span></span><br><span class="line">        <span class="keyword">if</span> (rs &gt;= SHUTDOWN &amp;&amp; (rs &gt;= STOP || workQueue.isEmpty())) &#123;</span><br><span class="line">            decrementWorkerCount();</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> wc = workerCountOf(c);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 是否允许超时：</span></span><br><span class="line"><span class="comment">         *  1.如果allowCoreThreadTimeOut为true，所有线程都允许超时</span></span><br><span class="line"><span class="comment">         *  2.如果allowCoreThreadTimeOut为false，只有超过corePoolSize之外的线程（也就是非核心线程）允许超时</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">boolean</span> timed = allowCoreThreadTimeOut || wc &gt; corePoolSize;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> ((wc &gt; maximumPoolSize || (timed &amp;&amp; timedOut)) <span class="comment">// 对超时线程进行回收</span></span><br><span class="line">            &amp;&amp; (wc &gt; <span class="number">1</span> || workQueue.isEmpty())) &#123;</span><br><span class="line">            <span class="keyword">if</span> (compareAndDecrementWorkerCount(c)) <span class="comment">// CAS修改workerCount，失败的话自选重试，直至成功</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Runnable r = timed ? workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) : workQueue.take(); <span class="comment">// 从队列中获取任务</span></span><br><span class="line">            <span class="keyword">if</span> (r != <span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">return</span> r;</span><br><span class="line">            timedOut = <span class="keyword">true</span>; <span class="comment">// 获取超时，下次自旋时进行回收</span></span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException retry) &#123;</span><br><span class="line">            timedOut = <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Execution-Flow-Of-Thread-Pool"><a href="#Execution-Flow-Of-Thread-Pool" class="headerlink" title="Execution Flow Of Thread Pool"></a>Execution Flow Of Thread Pool</h2><p>通过源码的分析，总结一下线程池工作的流程，如下图所示：<br><img src="/2020/10/08/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor2/001.png" alt="001"></p>

    </div>

    
    
    

      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/%E7%BA%BF%E7%A8%8B%E6%B1%A0/" rel="tag"><i class="fa fa-tag"></i> 线程池</a>
              <a href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" rel="tag"><i class="fa fa-tag"></i> 多线程</a>
              <a href="/tags/%E9%AB%98%E5%B9%B6%E5%8F%91/" rel="tag"><i class="fa fa-tag"></i> 高并发</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/09/27/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor1/" rel="prev" title="Java线程池之ThreadPoolExecutor（一）">
      <i class="fa fa-chevron-left"></i> Java线程池之ThreadPoolExecutor（一）
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/10/15/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E4%B9%8BThreadPoolExecutor3/" rel="next" title="Java线程池之ThreadPoolExecutor（三）">
      Java线程池之ThreadPoolExecutor（三） <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#A-Story-Mapping-Thread-Pool"><span class="nav-number">1.</span> <span class="nav-text">A Story Mapping Thread Pool</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Principle-Of-Thread-Pool"><span class="nav-number">2.</span> <span class="nav-text">Principle Of Thread Pool</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#The-Source-Code-Parsing"><span class="nav-number">3.</span> <span class="nav-text">The Source Code Parsing</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#execute"><span class="nav-number">3.1.</span> <span class="nav-text">execute</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#addWorker"><span class="nav-number">3.2.</span> <span class="nav-text">addWorker</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Worker"><span class="nav-number">3.3.</span> <span class="nav-text">Worker</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#runWorker"><span class="nav-number">3.4.</span> <span class="nav-text">runWorker</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#processWorkerExit"><span class="nav-number">3.5.</span> <span class="nav-text">processWorkerExit</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#getTask"><span class="nav-number">3.6.</span> <span class="nav-text">getTask</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Execution-Flow-Of-Thread-Pool"><span class="nav-number">4.</span> <span class="nav-text">Execution Flow Of Thread Pool</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="モンキーDルフィ"
      src="/images/lufei.jpg">
  <p class="site-author-name" itemprop="name">モンキーDルフィ</p>
  <div class="site-description" itemprop="description">海贼王におれはなる！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">18</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">15</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>
      <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=174419&auto=1&height=66"></iframe>
    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">モンキーDルフィ</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">66k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">1:01</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'rp9eaSA9Y6vBrWUdOf5ukLYs-gzGzoHsz',
      appKey     : 'SIkchhA5LF0xmXpXKtbkA65H',
      placeholder: "欢迎大家前来交流~",
      avatar     : '/images/lufei.jpg',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-CN' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
